﻿using HookupAppForm.Dto;
using Newtonsoft.Json;
using System;
using System.Windows.Forms;

namespace HookupAppForm.MyUserControl
{
    public partial class UserControlDropdown : UserControl
    {
        public delegate void SelectedChangeDelegate(object sender, EventArgs e);
        public event SelectedChangeDelegate selectedChangeEvent;
        public object selectedValue { get; set; }
        public string selectedText { get; set; }
        public UserControlDropdown()
        {
            InitializeComponent();
        }
        public void Init(string layout, string webAPI, int parentId = 0, string selectTxt = "")
        {
            try
            {
                string url = string.Format("api/services/app/HKP_Category/GetList?layout={0}&parentId={1}", layout, parentId);
                APIClient client = new APIClient(webAPI);
                var result = client.Get(url);
                ItemsDto<HKP_CategoryDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_CategoryDto>>(result);                
                comboBoxM.DisplayMember = "CateName";
                comboBoxM.ValueMember = "Id";
                comboBoxM.DataSource = res?.result?.items;
                if (res?.result?.items?.Length > 0 && string.IsNullOrEmpty(selectTxt))
                    selectedValue = res.result.items[0].Id;
                if (!string.IsNullOrEmpty(selectTxt))
                {
                    SetText(selectTxt);
                }
            }
            catch (Exception ex)
            {
                Utils.SysMsg(ex.Message, MessageBoxIcon.Error);
            }
        }
        public void SetValue(object val)
        {
            selectedValue = val;
            comboBoxM.SelectedValue = val;
        }
        public void SetText(string val)
        {
            selectedText = val;
            comboBoxM.Text = val;
        }
        private void comboBoxM_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectedValue = this.comboBoxM.SelectedValue;
            selectedText = this.comboBoxM.Text;

            if (selectedChangeEvent != null)
            {
                selectedChangeEvent(sender, e);
            }
        }
    }
}
